package com.yhsoft.flim.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsoft.benefitcard.entity.BatchGoods;
import com.yhsoft.benefitcard.entity.CardsBatch2;
import com.yhsoft.benefitcard.entity.CardsInfo;
import com.yhsoft.benefitcard.mapper.BatchGoodsMapper;
import com.yhsoft.benefitcard.mapper.CardsBatch2Mapper;
import com.yhsoft.benefitcard.service.IBatchGoodsService;
import com.yhsoft.benefitcard.service.ICardsInfoService;
import com.yhsoft.common.service.FuSiLingFlimApiService;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.flim.controller.po.FlimAddPricePo;
import com.yhsoft.flim.controller.po.JsonData;
import com.yhsoft.flim.controller.request.GetMoviePlansInVo;
import com.yhsoft.flim.entity.Cinema;
import com.yhsoft.flim.entity.HotMovie;
import com.yhsoft.flim.entity.MoviePlans;
import com.yhsoft.flim.mapper.MoviePlansMapper;
import com.yhsoft.flim.service.ICinemaService;
import com.yhsoft.flim.service.IHotMovieService;
import com.yhsoft.flim.service.IMoviePlansService;
import com.yhsoft.goods.entity.CompanyGoods;
import com.yhsoft.goods.mapper.CompanyGoodsMapper;
import com.yhsoft.goods.service.ICompanyGoodsService;
import com.yhsoft.goods.service.IGoodsInfoService;
import com.yhsoft.wxprogram.controller.response.BenefitCardOutVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 电影场次 服务实现类
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-12-05
 */
@Service
@Slf4j
public class MoviePlansServiceImpl extends ServiceImpl<MoviePlansMapper, MoviePlans> implements IMoviePlansService {

    @Resource
    private ICinemaService iCinemaService;

    @Resource
    private IHotMovieService iHotMovieService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CompanyGoodsMapper companyGoodsMapper;

    @Resource
    private ICardsInfoService iCardsInfoService;

    @Resource
    private IBatchGoodsService iBatchGoodsService;

    @Resource
    private BatchGoodsMapper batchGoodsMapper;

    @Resource
    private CardsBatch2Mapper batch2Mapper;

    @Resource
    private IGoodsInfoService iGoodsInfoService;

    @Override
    public void synJob() {
        List<Cinema> cinemaList = iCinemaService.list();
        List<HotMovie> hotMovieList = iHotMovieService.list();
        System.out.println(cinemaList.size());
        // 暂时先掉取上海地区的
        cinemaList = cinemaList.stream().filter(a -> a.getCityName().equals("上海")).collect(Collectors.toList());
        System.out.println(cinemaList.size());

        cinemaList.forEach(cinema -> {
            hotMovieList.forEach(hotMovie -> {
                try {
                    String msg = FuSiLingFlimApiService.moviePlansList(cinema.getId().toString(), hotMovie.getMovieId().toString());

                    JsonData moviePlansJson = JSON.parseObject(msg, JsonData.class);
                    List<MoviePlans> moviePlansList = JSON.parseArray(moviePlansJson.getData().toString(), MoviePlans.class);
                    moviePlansList.forEach((moviePlans) -> {
                        System.out.println(moviePlans.getShowId());
                        System.out.println(moviePlans.getMovieId());
                        moviePlans.setUpdatedTime(LocalDateTime.now());
                        moviePlans.setDeleted(0);
                    });
                    this.saveOrUpdateBatch(moviePlansList);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        });

    }

    @Override
    public List<MoviePlans> getMoviePlans(GetMoviePlansInVo inVo) {
        List<MoviePlans> moviePlansList = null;
        // 根据key从redis中查询场次信息，查不到就调接口
        String key = "MoviePlans:" + inVo.getCinemaId() + ":" + inVo.getMovieId();
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj != null) {
            // 解析
            moviePlansList = JSON.parseArray(obj.toString(), MoviePlans.class);
            // 过滤已开场的电影，
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            moviePlansList = moviePlansList.stream().filter(a -> LocalDateTime.parse(a.getShowStartTime(), df).isAfter(LocalDateTime.now())).collect(Collectors.toList());
            // 修改价格
            this.setAddPrice(moviePlansList);

            if (moviePlansList.size() > 0) {
                return moviePlansList;
            } else {
                return null;
            }
        }

        // 调福司令接口
        try {
            String msg = FuSiLingFlimApiService.moviePlansList(inVo.getCinemaId(), inVo.getMovieId());

            log.info(msg);

            JsonData moviePlansJson = JSON.parseObject(msg, JsonData.class);
            if (moviePlansJson.getData() == null || moviePlansJson.getData().size() == 0) {
                return null;
            }

            String data = moviePlansJson.getData().toString();

            // 存入redis,一小时失效
            redisTemplate.opsForValue().set(key, data, 60, TimeUnit.MINUTES);

            // 解析
            moviePlansList = JSON.parseArray(data, MoviePlans.class);

            // 修改价格
            this.setAddPrice(moviePlansList);

            return moviePlansList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public MoviePlans getMoviePlan(GetMoviePlansInVo inVo, String showId) {
        List<MoviePlans> moviePlansList = null;
        MoviePlans moviePlans = null;
        // 根据key从redis中查询场次信息
        String key = "MoviePlans:" + inVo.getCinemaId() + ":" + inVo.getMovieId();
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj != null) {
            // 解析
            moviePlansList = JSON.parseArray(obj.toString(), MoviePlans.class);
            // 过滤
            moviePlansList = moviePlansList.stream().filter(plan -> plan.getShowId().equals(showId)).collect(Collectors.toList());
            if (moviePlansList.size() == 1) {
                moviePlans = moviePlansList.get(0);
            }
        }
        return moviePlans;
    }

    @Override
    public void setMoviePlans(GetMoviePlansInVo inVo) throws IOException {
        log.info("小程序>电影模块>获取场次列表>刷新场次列表缓存数据");
        String key = "MoviePlans:" + inVo.getCinemaId() + ":" + inVo.getMovieId();

        String msg = FuSiLingFlimApiService.moviePlansList(inVo.getCinemaId(), inVo.getMovieId());

        log.info(msg);

        JsonData moviePlansJson = JSON.parseObject(msg, JsonData.class);
        if (moviePlansJson.getData() == null || moviePlansJson.getData().size() == 0) {
            return;
        }

        String data = moviePlansJson.getData().toString();

        // 存入redis,一小时失效
        redisTemplate.opsForValue().set(key, data, 60, TimeUnit.MINUTES);
    }

    private void setAddPrice(List<MoviePlans> moviePlansList) {
        // 获取电影加价信息
        FlimAddPricePo po = getAddPricePo();
        for (MoviePlans a : moviePlansList) {
            if (a.getSettlePrice() != null) {
                // 计算价格
                BigDecimal price = new BigDecimal(a.getSettlePrice());
                price = price.multiply(BigDecimal.ONE.add(po.getCharge()))
                        .add(po.getAddPrice().multiply(BigDecimal.valueOf(100)))
                        .add(po.getBatchAddPrice().multiply(BigDecimal.valueOf(100)))
                        .setScale(0, BigDecimal.ROUND_HALF_UP);
                a.setSettlePrice(price.intValue());
            }
        }
    }


    @Override
    public FlimAddPricePo getAddPricePo() {
        log.info("小程序>电影模块>修改价格");
        FlimAddPricePo po = new FlimAddPricePo();
        // 获取服务费和加价
        LambdaQueryWrapper<CompanyGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyGoods::getCompanyId, TokenService.getUserBytoken().getCompanyId());
        wrapper.eq(CompanyGoods::getGoodsId, 0);
        CompanyGoods companyGoods = companyGoodsMapper.selectOne(wrapper);
        if (companyGoods == null) {
            return po;
        }

        BigDecimal charge = companyGoods.getCustomCharge() != null ? new BigDecimal(companyGoods.getCustomCharge()).divide(new BigDecimal(100)) : BigDecimal.ZERO;
        BigDecimal addPrice = companyGoods.getFlimAddPrice() != null ? companyGoods.getFlimAddPrice() : BigDecimal.ZERO;
        log.info("获取此单位的平台服务费为:" + charge + "%");
        log.info("获取此单位商品管理电影模块的加价为:" + addPrice + "元");

        BigDecimal batchAddPrice = BigDecimal.ZERO;
        // 获取当前使用中福利卡的电影加价
        BenefitCardOutVo outVo = iCardsInfoService.getInUseCard();
        if (outVo != null) {
            log.info("获取当前使用中福利卡的电影加价");
            CardsInfo cardsInfo = iCardsInfoService.getById(outVo.getId());
            if (outVo.getCardType().equals("DYQ")) {
                LambdaQueryWrapper<CardsBatch2> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(CardsBatch2::getSecondBantchNum, cardsInfo.getSecondBantchNum());
                CardsBatch2 cardsBatch2 = batch2Mapper.selectOne(wrapper2);
                if (cardsBatch2 != null && cardsBatch2.getFlimBatchAddPrice() != null) {
                    batchAddPrice = cardsBatch2.getFlimBatchAddPrice();
                }
                log.info("当前使用中福利卡为电影券，该批次电影加价为:" + po.getBatchAddPrice() + "元");
            } else if (outVo.getCardType().equals("JFK")) {
                batchAddPrice = iGoodsInfoService.getMaxAddPrice(0);
                log.info("当前使用中福利卡为积分卡，电影最高加价为:" + batchAddPrice + "元");
            }
        }

        po.setCharge(charge);
        po.setAddPrice(addPrice);
        po.setBatchAddPrice(batchAddPrice);
        return po;
    }
}
